package com.cqupt.scanning.system.file.helper.utils;

import com.cqupt.scanning.handler.exception.MyException;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @Description: 前端接收 MultipartFile 转 File
 * @ClassName: MultipartFileToFile
 * @Date: 2020/12/4 18:09
 * @Author: 宋宝梁
 */


public class MultipartFileToFileUtil {

    /**
     * 转换并保存文件
     * @param file
     * @return
     * @throws IOException
     */
    public static File transferToFile(MultipartFile file, String savePath) throws IOException {
        File toFile = null;
        if (file.getSize() <= 0) {
            throw new MyException(20001, "文件内容为空");
        } else {
            InputStream ins = file.getInputStream();
            toFile = new File(savePath + File.separator + file.getOriginalFilename()); // 文件保存位置
            inputStreamToFile(ins, toFile);
        }
        return toFile;
    }

    /**
     * 获取流文件
     * @param ins
     * @param toFile
     */
    private static void inputStreamToFile(InputStream ins, File toFile) {
        OutputStream os = null;
        try {
            os = new FileOutputStream(toFile);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os!=null) os.close();
                if (ins!=null) ins.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

